package net.eearley.getco.app.base;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * The Class Keypad.
 */
abstract public class Keypad {

	/** The max height. */
	private int maxHeight;

	/** The max width. */
	private int maxWidth;

	/** The keys. */
	private Map<String, Key> keys;

	/** The layout. */
	private String[][] layout;

	/**
	 * Sets the key.
	 * 
	 * @param label
	 *            the label
	 * @param key
	 *            the key
	 */
	public void setKey(String label, Key key) {
		this.keys.put(label, key);
	}

	/**
	 * Gets the key.
	 * 
	 * @param id
	 *            the id
	 * 
	 * @return the key
	 */
	public Key getKey(String id) {
		return keys.get(id);
	}

	/**
	 * Gets the keys.
	 * 
	 * @return the keys
	 */
	public Map<String, Key> getKeys() {
		return keys;
	}

	/**
	 * Gets the layout.
	 * 
	 * @return the layout
	 */
	public String[][] getLayout() {
		return layout;
	}

	/**
	 * Gets the label.
	 * 
	 * @param key
	 *            the key
	 * 
	 * @return the label
	 */
	public String getLabel(Key key) {
		return layout[key.getXCoord()][key.getYCoord()];
	}

	public boolean isValid(Key key){
		return isValid(key.getCoords());
	}
	
	/**
	 * Checks if is valid.
	 * 
	 * @param coords
	 *            the coords
	 * 
	 * @return true, if is valid
	 */
	public boolean isValid(int[][] coords) {
		// check to make sure its not negative
		if ((coords[0][0] < 0) || (coords[0][1] < 0))
			return false;
		// then that we dont blow past the size
		if ((coords[0][0] > maxHeight) || (coords[0][1] > maxWidth))
			return false;
		// then check to make sure its not an inactive key
		String[] inactiveKeys = getInactiveKeys();
		for (int i = 0; i < inactiveKeys.length; i++) {
			String inactiveKey = inactiveKeys[i];
			if ((layout[coords[0][0]][coords[0][1]] == inactiveKey))
				return false;
		}
		return true;
	}

	/**
	 * Gets the inactive key.
	 * 
	 * @return the inactive key
	 */
	public abstract String[] getInactiveKeys();

	/**
	 * Instantiates a new keypad.
	 * 
	 * @param userLayout
	 *            the user layout
	 */
	public Keypad(String[][] userLayout) {
		this.keys = new HashMap<String, Key>();
		this.layout = userLayout;
		setup();
	}

	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer();
		Iterator<String> iterator = keys.keySet().iterator();
		while (iterator.hasNext()) {
			Object key = iterator.next();
			buf.append(key.toString());
			buf.append(" : ");
			buf.append(keys.get(key).toString());
		}
		return buf.toString();
	}

	/**
	 * Setup.
	 */
	private void setup() {
		for (int i = 0; i < layout.length; i++) {
			for (int j = 0; j < layout[i].length; j++) {
				keys.put(layout[i][j], new Key(i, j));
				if (i > maxHeight)
					maxHeight = i;
				if (j > maxWidth)
					maxWidth = j;
			}
		}
	}
}
